<!-- 二维分析图 -->
<template>
  <div style="">
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="0"
          :searchWord="searchWord"
          @getChartData="setParams"
        ></ChooseScreen>
        <div class="chooseScreenDiv">
          X轴
          <el-select v-model="xCategory" size="small" style="width: 120px;">
            <el-option
              v-for="item in categoryOptionsX"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.value"
              :key="item.id"
            ></el-option>
          </el-select>
          Y轴
          <el-select v-model="yCategory" size="small" style="width: 120px;">
            <el-option
              v-for="item in categoryOptionsY"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.value"
              :key="item.id"
            ></el-option>
          </el-select>
          <button
            size="small"
            class="confirmBtn"
            @click="getChartData()"
            type=""
            style=""
          >
            确认
          </button>
        </div>
      </template>
      <template slot="chart">
        <ChartFPatent
          v-if="dbid == 'patent' && chartData && chartData.length > 0"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
        />
        <ChartFPaper
          v-if="dbid == 'paper' && chartData && chartData.length > 0"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
        <!-- <p v-else style="text-align:center;line-height: 100px;">暂无数据</p> -->
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
        <i class="icon el-icon-full-screen" @click="handleFullScreen">&nbsp;全屏</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">{{ ite }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartFPatent from "../charts/ChartFPatent";
import ChartFPaper from "../charts/ChartFPaper";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object
    },
    dcData: {
      type: Object
    }
  },
  components: {
    CSlot,
    ChartFPatent,
    ChartFPaper,
    ChooseScreen
  },
  data() {
    return {
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      selectATit: "top5", // 筛选条件A，动态
      timeType: "", // 设置时间筛选类型
      chartId: "", // 图表id名称
      //
      chartData: [],
      chartType: "line",
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      xCategory: "",
      yCategory: "",
      categoryOptionsX: [],
      categoryOptionsY: [],

      xCategory_paper: "authors.org.keyword",
      yCategory_paper: "keywords.keyword",

      categoryOptionsX_paper: [
        {
          label: "国家",
          value: "authors.country.keyword",
          disabled: false
        },
        {
          label: "发表年份",
          value: "year",
          disabled: false
        },
        {
          label: "作者",
          value: "authors.name.keyword",
          disabled: false
        },
        {
          label: "机构",
          value: "authors.org.keyword",
          disabled: false
        },
        {
          label: "期刊",
          value: "venue_name.keyword",
          disabled: false
        },
        {
          label: "关键词",
          value: "keywords.keyword",
          disabled: true
        }
      ],
      categoryOptionsY_paper: [
        {
          label: "国家",
          value: "authors.country.keyword",
          disabled: false
        },
        {
          label: "发表年份",
          value: "year",
          disabled: false
        },
        {
          label: "作者",
          value: "authors.name.keyword",
          disabled: false
        },
        {
          label: "机构",
          value: "authors.org.keyword",
          disabled: false
        },
        {
          label: "期刊",
          value: "venue_name.keyword",
          disabled: false
        },
        {
          label: "关键词",
          value: "keywords.keyword",
          disabled: true
        }
      ],

      xCategory_patent: "isd",
      yCategory_patent: "an.keyword",
      categoryOptionsX_patent: [
        {
          label: "申请年份",
          value: "apd",
          disabled: false
        },
        {
          label: "公开年份",
          value: "isd",
          disabled: false
        },
        {
          label: "国家",
          value: "nd",
          disabled: false
        },
        {
          label: "机构",
          value: "an.keyword",
          disabled: true
        },
        {
          label: "发明人",
          value: "in",
          disabled: false
        },
        {
          label: "技术领域",
          value: "ipc",
          disabled: false
        }
      ],
      categoryOptionsY_patent: [
        {
          label: "申请年份",
          value: "apd",
          disabled: false
        },
        {
          label: "公开年份",
          value: "isd",
          disabled: true
        },
        {
          label: "国家",
          value: "nd",
          disabled: false
        },
        {
          label: "机构",
          value: "an.keyword",
          disabled: false
        },
        {
          label: "发明人",
          value: "in",
          disabled: false
        },
        {
          label: "技术领域",
          value: "ipc",
          disabled: false
        }
      ],
      tableData: {
        tit: [],
        content: []
      },
      yearArr: [],
      emptyText: "数据加载中...",
      size: 10,
      startYear: "2012",
      endYear: "2022",
      dbid: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: ""
    };
  },
  computed: {
    ...mapState(["searchWord"])
  },
  watch: {
    // chartTempl() {
    //   this.dbid = this.$route.query.type || this.$route.query.dbid;
    //   this.init();
    // },
    dcData() {
      this.dbid = this.$route.query.type || this.$route.query.dbid;
      this.init();
    },
    xCategory(val) {
      this.categoryOptionsY.map((item, i) => {
        item.disabled = false;
        if (val == item.value) {
          item.disabled = true;
        }
      });
    },
    yCategory(val) {
      this.categoryOptionsX.map((item, i) => {
        item.disabled = false;
        if (val == item.value) {
          item.disabled = true;
        }
      });
    }
  },
  mounted() {
    this.dbid = this.$route.query.type || this.$route.query.dbid;
    // this.init();
  },
  methods: {
    init() {
      if (this.dbid == "patent") {
        this.xCategory = this.xCategory_patent;
        this.yCategory = this.yCategory_patent;
        this.categoryOptionsX = this.categoryOptionsX_patent;
        this.categoryOptionsY = this.categoryOptionsY_patent;
      } else {
        this.xCategory = this.xCategory_paper;
        this.yCategory = this.yCategory_paper;
        this.categoryOptionsX = this.categoryOptionsX_paper;
        this.categoryOptionsY = this.categoryOptionsY_paper;
      }
      this.chartId = "chart" + this.chartTempl.id;
      this.tname = this.chartTempl.tname;
      this.chartData = this.dcData.chartData;

      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      this.loading = false;
    },
    //
    setParams(Params) {
      this.startYear = Params.startYear;
      this.endYear = Params.endYear;
      this.size = Params.size;
      this.getChartData();
    },
    getChartData() {
      this.loading = true;
      if (this.xCategory == this.yCategory) {
        this.$message.warning("x轴所选维度不能与y轴相同");
        this.loading = false;
        return;
      }
      let ths = this;
      if (this.cancel !== null) {
        this.cancel();
      }
      let sq = `${this.timeType}>=${this.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${this.endYear}${this.datefieldformatTxt}`;
      if (this.searchWord !== "") {
        sq = `${this.searchWord} AND ` + sq;
      }
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: []
      };
      let _aggs = [];
      if (this.dbid == "patent") {
        _aggs = [
          {
            field: this.yCategory,
            size: this.size,
            aggs: [{ field: this.xCategory }]
          }
        ];
      } else if (this.dbid == "paper") {
        _aggs = [
          {
            action: "trend_statistic.StaticTrendDataDetail",
            parameters: {
              search_type: "2DAnalysis",
              two_d_parm: `${this.xCategory}-${this.yCategory}-${5}`
            }
          }
        ];
      }
      let params = {
        aggs: _aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: ""
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let familyFlag = localStorage.getItem("familyFlag") || false;
      if (familyFlag ==1 ) {
        params["familyFlag"] = true; // 同族合并
        params["tzzlhb"] = false; // 同专利合并
      } else if (familyFlag ==2) {
        params["familyFlag"] = false; // 同族合并
        params["tzzlhb"] = true; // 同专利合并
      }
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
          ths.loading = false;
        })
      })
        .then(res => {
          this.chartData = res.data.chartData;
          this.$store.commit("setTotalTxt", res.data.total);
          //如果是时间 则排序
          if(this.xCategory == "year" || this.yCategory == "year"){
            this.chartData &&
            this.chartData.map((item, index) => {
              item.aggregation.items.sort(function (a, b) {
                return Number(a.term) - Number(b.term); // 返回负值表示交换位置
              });
            });
            this.chartData.sort(function (a, b) {
                return Number(a.key) - Number(b.key); // 返回负值表示交换位置
            });
          }
          this.loading = false;
        })
        .catch(err => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef
      if (!element) {
        return
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    }
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  }
};
</script>

<style lang="scss">
.chooseScreenDiv {
  margin-top: 10px;
  // position: absolute;
  // top: 0;
  // left: 530px;
  color: #9e9e9e;
  font-size: 12px;
}
.confirmBtn {
  width: 100px;
  height: 30px;
  border-color: $mainColor;
  border-radius: 15px;
  font-size: 12px;
  color: #f7f7f7;
  background-color: $mainColor;
  cursor: pointer;
  margin-left: 20px;
}
.slot-box {
  min-height: 300px;
}
</style>
